﻿using System;
//////////////////////
////Source: http://subversion.assembla.com/svn/outcoldman_p 
/////////////////////
namespace FU.Capstones.IMS.Web.Common.InventoryServiceProxy.DataContracts
{
	public class PropertyValidation<TBindingModel>
		where TBindingModel : BindingModelBase<TBindingModel>
	{
		private Func<TBindingModel, bool> validationCriteria;
		private string errorMessage;
		private readonly string propertyName;

		public PropertyValidation(string propertyName)
		{
			this.propertyName = propertyName;
		}
        /// <summary>
        /// This method aims to add the condition to validate the chosen property
        /// </summary>
        /// <param name="xvalidationCriteria">
        /// The function handle the validating condition
        /// </param>
        /// <returns></returns>
		public PropertyValidation<TBindingModel> When(Func<TBindingModel, bool> xvalidationCriteria)
		{
			if (validationCriteria != null)
				throw new InvalidOperationException("You can only set the validation criteria once.");

			validationCriteria = xvalidationCriteria;
			return this;
		}

        /// <summary>
        /// This method is used for setting up the error message for the invalid case.
        /// </summary>
        /// <param name="xerrorMessage">
        /// The message to be shown in case of error.
        /// </param>
        /// <returns></returns>
		public PropertyValidation<TBindingModel> Show(string xerrorMessage)
		{
			if (errorMessage != null)
				throw new InvalidOperationException("You can only set the message once.");

			errorMessage = xerrorMessage;
			return this;
		}
        /// <summary>
        /// This method is to check whether the chosen object is invalid or not.
        /// </summary>
        /// <param name="presentationModel">
        /// The object to be checked.
        /// </param>
        /// <returns></returns>
		public bool IsInvalid(TBindingModel presentationModel)
		{
			if (validationCriteria == null)
				throw new InvalidOperationException(
					"No criteria have been provided for this validation. (Use the 'When(..)' method.)");

			return validationCriteria(presentationModel);
		}

		public string ErrorMessage
		{
            get
            {
                if (errorMessage == null)
                    throw new InvalidOperationException(
                        "No error message has been set for this validation. (Use the 'Show(..)' method.)");

                return errorMessage;
            }
		}

		public string PropertyName
		{
			get { return propertyName; }
		}
	}
}